<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <div class="filter-item">
        <el-input v-model="userQuery.param.userName" placeholder="请输入用户名" style="width: 200px;" clearable></el-input>
        <el-select style="margin-left:10px;" v-model="userQuery.param.roleId" placeholder="请选择" clearable>
          <el-option v-for="item in roleLists" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="handleUserFilter" style="margin-left:10px;">
          查询
        </el-button>
        <el-button v-if="add_user_button_status" icon="el-icon-plus" @click="handleAddUser" style="margin-left:10px;">
          增加
        </el-button>
      </div>
    </div>

    <el-table :data="userLists" style="width: 100%">
      <el-table-column v-if="false" prop="id"></el-table-column>
      <el-table-column v-if="false" prop="roleIds"></el-table-column>
      <el-table-column label="账号" prop="userName"></el-table-column>
      <el-table-column label="昵称" prop="nickName"></el-table-column>
      <el-table-column label="性别" prop="sex">
        <template slot-scope="scope">
          {{scope.row.sex === 0 ? '男' : '女'}}
        </template>
      </el-table-column>
      <el-table-column label="手机" prop="phoneNumber"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="角色" prop="roles"></el-table-column>
      <el-table-column fixed="right" label="操作" width="300" v-if="upd_user_button_status || upd_role_button_status || upd_password_button_status">
        <template slot-scope="scope">
          <el-button v-if="upd_user_button_status" type="primary" icon="el-icon-edit" size="mini" @click="handleEditUser(scope.row)">编辑</el-button>

          <el-popover v-if="upd_role_button_status" :ref="'newRolesPopover' + scope.row.id" placement="left" width="160" trigger="click" style="margin-left:10px;" @show="newRoleIdsShow(scope.row.roleIds)" @after-leave="newRoleIdsClose">
            <el-checkbox-group v-model="newRoleIds">
              <el-checkbox v-for="role in roleLists" :key="role.id" :label="role.id">{{role.name}}</el-checkbox>
            </el-checkbox-group>
            <div style="text-align: right; margin-top:10px">
              <el-button type="primary" size="mini" @click="handleUpdRoles(scope.row.id)">确定</el-button>
            </div>
            <el-button slot="reference" type="warning" icon="el-icon-user" size="mini" style="margin-left:10px;">角色</el-button>
          </el-popover>

          <el-popover v-if="upd_password_button_status" :ref="'newPwdPopover' + scope.row.id" placement="left" width="160" trigger="click" style="margin-left:10px;" @after-leave="newPwdClose">
            <div>新密码：</div>
            <el-input v-model="newPassword" show-password size="mini"></el-input>
            <div style="text-align: right; margin-top:10px">
              <el-button type="primary" size="mini" @click="handleUpdPwd(scope.row.id)">确定</el-button>
            </div>
            <el-button slot="reference" type="danger" icon="el-icon-lock" size="mini">密码</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleUserSizeChange" @current-change="handleUserCurrentChange" :current-page="userQuery.page" :page-sizes="[20, 50, 100]" :page-size="userQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="totalUser">
    </el-pagination>

    <el-dialog :title="textMap[userFormDialogStatus]" :visible.sync="dialogUserFormVisible" :close-on-click-modal="false" width="45%">
      <el-form :rules="userFormRules" ref="userform" :model="userForm" label-width="80px">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="userForm.userName" :disabled="userFormDialogStatus!=='create'"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="userFormDialogStatus==='create'" prop="password">
          <el-input v-model="userForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userForm.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds" v-if="userFormDialogStatus==='create'">
          <el-select v-model="userForm.roleIds" multiple clearable>
            <el-option v-for="item in roleLists" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="resetUserForm()">
          取 消
        </el-button>
        <el-button v-if="userFormDialogStatus==='create'" type="primary" @click="handleCreateUser()">
          确 定
        </el-button>
        <el-button v-if="userFormDialogStatus==='update'" type="primary" @click="handleUpdateUser()">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { mapGetters } from 'vuex';
import {
  addUser, updUser, updUserPwd, getAllUser
} from '@/api/user'

import {
  bindUserRoles, getAllRoles
} from '@/api/role'
import { valid } from 'mockjs';

export default {
  name: 'userInfo',
  created() {
    this.getRoleLists();
    this.handleUserFilter();
    if (this.elements['add_user']) {
      this.add_user_button_status = true;
    }
    if (this.elements['upd_user']) {
      this.upd_user_button_status = true;
    }
    if (this.elements['upd_user_role']) {
      this.upd_role_button_status = true;
    }
    if (this.elements['upd_user_password']) {
      this.upd_password_button_status = true;
    }
  },
  computed: {
    ...mapGetters(["elements"])
  },
  data() {
    return {
      textMap: {
        create: '创建',
        update: '修改'
      },
      dialogUserFormVisible: false,
      userFormDialogStatus: '',
      roleQuery: {
        page: 1,
        size: 2147483640,
        param: {
          code: undefined,
          name: undefined
        }
      },
      userQuery: {
        page: 1,
        size: 20,
        param: {
          roleId: undefined,
          userName: undefined
        }
      },
      roleLists: [],
      userLists: [],
      userForm: {
        id: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        sex: undefined,
        phoneNumber: undefined,
        email: undefined,
        roleIds: undefined
      },
      userFormRules: {
        userName: [
          { required: true, message: "请填写账号名称", trigger: "blur" },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "请填写昵称", trigger: "blur" },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: "请填写密码", trigger: "blur" },
          { min: 0, max: 30, message: '长度在 0 到 30 个字符', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: "请填写性别", trigger: "blur" },
        ],
        phoneNumber: [
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: "请选择角色", trigger: "blur" },
        ]
      },
      newPassword: '',
      newRoleIds: [],
      totalUser: 0,
      successCode: 20000,

      add_user_button_status: false,
      upd_user_button_status: false,
      upd_role_button_status: false,
      upd_password_button_status: false,

    }
  },
  methods: {
    getRoleLists() {
      getAllRoles(this.roleQuery).then(resp => {
        if (resp.code === this.successCode) {
          this.roleLists = resp.datas.datas;
        }
      });
    },
    getUserLists() {
      getAllUser(this.userQuery).then(resp => {
        if (resp.code === this.successCode) {
          this.userLists = resp.datas.datas;
          this.totalUser = resp.datas.total;
        }
      })
    },
    handleUserFilter() {
      this.userQuery.page = 1;
      this.getUserLists();
    },
    handleAddUser() {
      this.resetUserForm();
      this.dialogUserFormVisible = true;
      this.userFormDialogStatus = 'create';
    },
    handleCreateUser() {
      this.$refs['userform'].validate(valid => {
        if (!valid) {
          return false;
        }
        // if (!this.userForm.roleIds || this.userForm.roleIds.length === 0) {
        //   this.$refs['userform'].validateField("roleIds");
        //   console.log("表单角色校验不通过");
        //   return false;
        // }
        // if (!this.userForm.password || this.userForm.password === "") {
        //   this.$refs['userform'].validateField("password");
        //   console.log("表单密码校验不通过");
        //   return false;
        // }
        addUser(this.userForm).then(resp => {
          if (resp.code === this.successCode) {
            this.resetUserForm();
            this.handleUserFilter();
          }
        });
      });
    },
    handleEditUser(row) {
      this.resetUserForm();
      this.dialogUserFormVisible = true;
      this.userFormDialogStatus = 'update';
      this.$nextTick(() => {
        this.userForm = {
          id: row.id,
          userName: row.userName,
          nickName: row.nickName,
          sex: row.sex,
          phoneNumber: row.phoneNumber,
          email: row.email
        }
      })
    },
    handleUpdateUser() {
      this.$refs['userform'].validate(valid => {
        if (!valid) {
          return false;
        }
        updUser(this.userForm).then(resp => {
          if (resp.code === this.successCode) {
            this.resetUserForm();
            this.handleUserFilter();
          }
        });
      });
    },
    handleUpdRoles(id) {
      if (!this.newRoleIds || this.newRoleIds.length <= 0) {
        this.$notify({
          title: "失败",
          message: "请选择角色",
          type: "warning",
          duration: 2000
        });
        return;
      }
      bindUserRoles({
        UserId: id,
        RoleId: this.newRoleIds
      }).then(resp => {
        if (resp.code === this.successCode) {
          this.$notify({
            title: "成功",
            message: "角色修改成功",
            type: "success",
            duration: 2000
          });
          this.$refs['newRolesPopover' + id].doClose();
          this.getUserLists();
        }
      })
    },
    handleUpdPwd(id) {
      if (!this.newPassword || this.newPassword === "") {
        this.$notify({
          title: "失败",
          message: "请填写密码",
          type: "warning",
          duration: 2000
        });
        return;
      }
      updUserPwd({
        UserId: id.toString(),
        Password: this.newPassword
      }).then(resp => {
        if (resp.code === this.successCode) {
          this.$notify({
            title: "成功",
            message: "密码修改成功",
            type: "success",
            duration: 2000
          });
          this.$refs['newPwdPopover' + id].doClose();
        }
      });
    },
    resetUserForm() {
      this.dialogUserFormVisible = false;
      this.userFormDialogStatus = '';
      if (this.$refs['userform']) {
        this.$refs['userform'].resetFields();
      }
      // console.log(this.userForm);
    },
    newPwdClose() {
      this.newPassword = '';
    },
    newRoleIdsClose() {
      this.newRoleIds = [];
    },
    newRoleIdsShow(roleIds) {
      this.newRoleIds = roleIds.map(item => {
        return item.toString()
      });
    },
    handleUserSizeChange(val) {
      this.userQuery.size = val;
      this.getUserLists();
    },
    handleUserCurrentChange(val) {
      this.userQuery.page = val;
      this.getUserLists();
    }
  }
}
</script>

